﻿using ProtoBuf;
using ProtoBuf.Meta;
using System;
using System.ComponentModel;
using System.IO;
using UnityEngine;

namespace CGF
{
    /**
     * 协议体格式
    [ProtoContract]
    public class sc_data
    {
        [ProtoMember(1)]
        public int uid;

        [ProtoMember(2)]
        public int score;

        [ProtoMember(3)]
        public int age;
    }
    */

    public static class ProtobufHelper
    {
        public static T ToObject<T>(byte[] bytes)
        {
            return (T)ToObject(bytes, typeof(T));
        }

        public static object ToObject(byte[] bytes, Type type)
        {
            if (bytes == null)
            {
                Debug.LogError("传入的 bytes 为 null");
                return null;
            }
            using (MemoryStream stream = new MemoryStream(bytes, 0, bytes.Length))
            {
                object o = RuntimeTypeModel.Default.Deserialize(stream, null, type);
                if (o is ISupportInitialize supportInitialize)
                {
                    supportInitialize.EndInit();
                }
                return o;
            }
        }

        public static byte[] ToBytes(object message)
        {
            if (message == null)
            {
                Debug.LogError("传入的 message 为 null");
                return null;
            }
            using (MemoryStream stream = new MemoryStream())
            {
                Serializer.Serialize(stream, message);
                return stream.ToArray();
            }
        }

        public static void ToStream(object message, MemoryStream stream)
        {
            Serializer.Serialize(stream, message);
        }

        public static T ToObject<T>(MemoryStream stream)
        {
            return (T)ToObject(stream, typeof(T));
        }

        public static object ToObject(MemoryStream stream, Type type)
        {
            if (stream == null)
            {
                Debug.LogError("传入的 stream 为 null");
                return null;
            }
            object o = RuntimeTypeModel.Default.Deserialize(stream, null, type);
            if (o is ISupportInitialize supportInitialize)
            {
                supportInitialize.EndInit();
            }
            return o;
        }
    }
}
